import 'package:flutter/material.dart';
import 'package:flutter_base/base/controller/base_controller.dart';
import 'package:flutter_base/http/http_export.dart';
import 'package:flutter_base/user/app_user_manager.dart';
import 'package:flutter_base/utils/loading/loading_utils.dart';
import 'package:flutter_base/utils/log/utils_log.dart';
import 'package:flutter_base/widgets/dialog/common_normal_sheet.dart';
import 'package:flutter_base/widgets/dialog/gender_selector_widget.dart';
import 'package:flutter_base/widgets/dialog/date_picker_widget.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

class SettingProfileLogic extends BaseController {
  // 用户名输入控制器
  final TextEditingController nameController = TextEditingController();
  final FocusNode nameFocusNode = FocusNode();

  // 性别选择 (1: 男, 2: 女)
  final selectedGender = 1.obs;

  // 生日
  final birthday = DateTime.now().obs;
  final birthdayText = ''.obs;

  @override
  void onInit() {
    super.onInit();

    // 初始化用户名
    nameController.text = AppUserManager().user.value?.username ?? '';

    // 初始化性别
    selectedGender.value = AppUserManager().user.value?.sex ?? 1;

    nameFocusNode.addListener(() {
      update();
    });
  }

  @override
  void onClose() {
    nameController.dispose();
    nameFocusNode.dispose();
    super.onClose();
  }

  // 显示性别选择器
  void showGenderSelector() {
    CommonNormalSheet(
      title: '选择性别',
      bodyWidget: Obx(() {
        return GenderSelectorWidget(
          selectedGender: selectedGender.value == 1 ? 'male' : 'female',
          onGenderSelected: (gender) {
            // Get.back();
            selectedGender.value = gender == 'male' ? 1 : 2;
            // 性别更改后立即保存

          },
        );
      }),
      showCancel: false,
      onSure: () {
        saveProfile(sex: selectedGender.value);
      },
      // autoDismiss: false,
    ).show();
  }

  // 显示日期选择器
  void showDatePicker() {
    DateTime nowTime = DateTime.now();
    DateTime lastDate = DateTime(nowTime.year - 18, nowTime.month, nowTime.day);
    // DateTime.now().subtract(Duration(yea))
    CommonNormalSheet(
      title: 'Date of Birth',
      bodyWidget: DatePickerWidget(
        initialDate: birthday.value,
        firstDate: DateTime(1950),
        lastDate: lastDate, // Must be under 18 years old
        onDateSelected: (date) {
          birthday.value = date;
          birthdayText.value = DateFormat('yyyy.MM.dd').format(date);
        },
      ),
      showCancel: true,
      cancelText: 'Cancel',
      sureText: 'Confirm',
      // onCancel: () => Get.back(),
      // onSure: () => Get.back(),
      onSure: () {
        // Format birthday to ISO string with timezone offset
        String formattedBirthday = birthday.value.toIso8601String();

        clog('message   $formattedBirthday');
        clog('Selected birthday: ${birthday.value}');
        
        saveProfile(birthday: formattedBirthday);
      },
    ).show();
  }

  // 处理键盘完成按钮事件
  void handleNameSubmitted(String value) {
    if (value.trim().isNotEmpty) {
      saveProfile(username: value.trim());
    }
  }

  // 保存个人资料
  void saveProfile({
    String? avatar,
    String? username,
    String? birthday,
    int? sex,
  }) async {
    // 如果传入了用户名，使用传入的值，否则使用输入框中的值
    // final name = username ?? nameController.text.trim();
    //
    // if (name.isEmpty && username != null) {
    //   LoadingUtils.showToast('Please enter your name');
    //   return;
    // }

    // LoadingUtils.showLoading(status: 'Updating...');

    HttpResponse response = await AppUserManager.updateUserInfoToServer(
      avatar: avatar, 
      username: username ??AppUserManager().user.value?.username,
      birthday: birthday, 
      sex: sex,
      showLoading: true
    );


    // LoadingUtils.dismiss();
    
    if (response.isSuccess) {
      LoadingUtils.showToast('Profile updated successfully');
      // 只有在保存完整个人资料时才返回上一页
      AppUserManager().refreshUserInfo();
      if (username != null && birthday != null && sex != null) {
        Get.back();
      }
    }
  }
}
